<template>
  <div v-if="rightBoxAuth">
    <transition name="moveR1">
      <div>
        <div class="toolBox" :class="isVisible ? '' : 'searchToolBox'">
          <div
            ref="searchBox"
            class="searchBox"
            :class="isVisible ? '' : 'searchRinhtBox'"
          >
            <div class="searchInfo">
              <div class="searchBtn" @click.stop="showsearchName">
                <i class="icons el-icon-place"></i>
              </div>
              <div
                class="searchInfoBtn"
                v-show="isShowSearchName"
                @click.stop="searchName()"
              >
                <i class="el-icon-search" />
              </div>
              <el-input
                style="flex: 1"
                v-show="false"
                ref="inputRefsearchInfo"
                v-model="inputName"
                type="text"
                clearable
                placeholder="搜地点"
              />

              <el-autocomplete
                v-show="isShowSearchName"
                ref="inputRefsearchInfo"
                v-model="inputName"
                clearable
                placeholder="搜地点"
                :fetch-suggestions="historySearch"
                @select="handleSelectHistory"
              >
                <template
                  slot-scope="{ item }"
                  popper-class="input-with-select"
                >
                  <div class="historyItem">
                    <svg-icon class="history-icon" icon-class="history" />
                    <div class="history-text">{{ item }}</div>
                  </div>
                </template>
              </el-autocomplete>
            </div>

            <div
              v-if="searchPointsList.length > 0 && isShowSearchName"
              class="searchList"
            >
              <div
                v-for="(item, index) in searchPointsList"
                :key="index"
                class=""
                @click="getSearchLocation(item, index)"
              >
                <i class="iconp el-icon-location-outline" />
                <div>
                  {{ item.name }}
                </div>
                <div>
                  {{ item.district }} &nbsp;&nbsp;
                  <span v-show="item.address.length > 0">{{
                    item.address
                  }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 测量工具 -->
          <div class="measureBox"><tools></tools></div>
        </div>

        <div v-show="isVisible" ref="Rwindow" class="container container_right">
          <div class="title">
            <div class="t icon" @click="isShowModule(false)">
              <svg-icon icon-class="shousuo_R" />
            </div>
            <div class="titleText">
              <div
                class="t"
                :class="{ active: moduleIndex == 4 }"
                v-if="warning_query_auth"
                @click="changeModule(4)"
              >
                预警信息
              </div>
              <div
                class="t"
                :class="{ active: moduleIndex == 5 }"
                v-if="order_query_auth"
                @click="changeModule(5)"
              >
                指点任务
              </div>
              <div
                class="t"
                :class="{ active: moduleIndex == 6 }"
                v-if="search_photo_query_auth"
                @click="changeModule(6)"
              >
                时空搜图
              </div>
            </div>
          </div>
          <div class="box">
            <View4
              v-if="moduleIndex == 4"
              :date-value="dateValue"
              v-on="$listeners"
            />
            <View5
              ref="view5"
              v-if="moduleIndex == 5"
              v-on="$listeners"
              v-bind="$attrs"
              :date-value="dateValue"
            />
            <View6 v-if="moduleIndex == 6" :date-value="dateValue" />
          </div>
        </div>
        <div
          v-show="!isVisible"
          class="showbtn icon"
          @click="isShowModule(true)"
        >
          <svg-icon icon-class="shousuo_L" />
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import View4 from "./tab-views/view4.vue";
import View5 from "./tab-views/view5.vue";
import View6 from "./tab-views/view6.vue";
import Tools from "./rightComponent/tools.vue";

import { locationDistrict } from "@/api/censuisdata";
import { gcj02towgs84 } from "@/utils/index.js";
var IconLocateLayer = null;

const nowTimes = Date.now();
const oldTimes = nowTimes - 86400000 * 30;
const getDate = (time) => {
  if (time) {
    const val = new Date(time);
    const Y = val.getFullYear();
    const M = val.getMonth() + 1;
    const D = val.getDate();
    return Y + "-" + M + "-" + D;
  }
  return "";
};
const startDate = getDate(oldTimes); // 一个月前的时间
const endDate = getDate(nowTimes); // 今天的时间

export default {
  name: "Right",
  components: {
    View4,
    View5,
    View6,
    Tools,
  },
  data() {
    return {
      moduleIndex: 4,
      isVisible: true,
      dateValue: [startDate, endDate],
      inputName: "",
      searchPointsList: [],
      searchPointsIndex: null,
      isShowSearchName: false,

      userAuthor: null,
      orgInfo: null,
    };
  },
  computed: {
    // 预警信息显示权限
    warning_query_auth() {
      return this.userAuthor?.warning?.query?.have_auth;
    },
    // 指点任务显示权限
    order_query_auth() {
      return this.userAuthor?.order?.query?.have_auth;
    },
    // 时空搜图显示权限
    search_photo_query_auth() {
      return this.userAuthor?.search_photo?.query?.have_auth;
    },
    // 右侧看板显示
    rightBoxAuth() {
      return (
        this.warning_query_auth ||
        this.order_query_auth ||
        this.search_photo_query_auth
      );
    },
  },
  created() {
    this.userAuthor = this.$store.getters.userAuth;
  },
  mounted() {
    console.log(1);
    this.initData();
    this.initBus();
  },
  methods: {
    initData() {
      var that = this;
      this.orgInfo = this.$store.getters.orgDeptList.find((org) => {
        return org.dept_id == this.$store.getters.orgId;
      });

      // 修改高度
      window.onresize = function temp() {};
      window.addEventListener("click", (event) => {
        const e = event || window.event;
        if (that.$refs.searchBox && !that.$refs.searchBox.contains(e.target)) {
          that.isShowSearchName = false;
        }
      });

      console.log("data");
      let option = this.$store.getters.kanBanConfig;
      if (!option.option) {
        return;
      }
      let find = option.option.find((feature) => {
        return feature.position == "right";
      });

      if (!!find) {
        console.log("right", find);
        if (find.status === 2) {
          this.isVisible = true;
        } else {
          this.isVisible = false;
        }

        switch (find.feature) {
          case "warning":
            if (this.warning_query_auth) {
              this.moduleIndex = 4;
            } else {
              if (this.order_query_auth) {
                this.moduleIndex = 5;
              } else {
                this.moduleIndex = 6;
              }
            }
            break;
          case "order":
            if (this.order_query_auth) {
              this.moduleIndex = 5;
            } else {
              if (this.warning_query_auth) {
                this.moduleIndex = 4;
              } else {
                this.moduleIndex = 6;
              }
            }
            break;
          case "search_photo":
            if (this.search_photo_query_auth) {
              this.moduleIndex = 6;
            } else {
              if (this.warning_query_auth) {
                this.moduleIndex = 4;
              } else {
                this.moduleIndex = 5;
              }
            }
            break;
          default:
            break;
        }
        that.$nextTick(() => {
          if (that.moduleIndex != 4) {
            console.log("CloseLoadingCloseLoading");
            that.$bus.emit("CloseLoading");
          }
        });
      } else {
        this.isVisible = true;
      }
    },
    initBus() {
      console.log("bus");
      this.$bus.on("ChangeRightHeight", (data) => {
        console.log(data);
        if (data == "in") {
          this.$refs.Rwindow.style.height = "120px";
        } else {
          this.$refs.Rwindow.style.height = "92.59%";
        }
      });

      // 搜索日期变化
      this.$bus.on("changeDateValue", (data) => {
        this.dateValue = data;
        console.log("changeDateValue", this.dateValue);
      });
    },
    removeBus() {
      this.$bus.off("ChangeRightHeight");
      this.$bus.off("changeDateValue");
    },
    showsearchName() {
      var _this = this;
      _this.isShowSearchName = !_this.isShowSearchName;
      if (this.isShowSearchName == true) {
        window.addEventListener("keyup", _this.KeyDownKeyword, true);
        setTimeout(() => {
          this.$refs.inputRefsearchInfo.focus();
        }, 5);
      } else {
        window.removeEventListener("keyup", _this.KeyDownKeyword, true);
      }
    },
    KeyDownKeyword(e) {
      console.log(e.key, e.keyCode);
      var _this = this;
      if (e.keyCode == 32) {
        _this.searchName();
      }
    },
    getSearchLocation(item) {
      console.log("getSearchLocation", item);
      this.saveHistory(item.name);
      var _this = this;
      // var lon = gcj02towgs84(
      //   parseFloat(item.location[0]),
      //   parseFloat(item.location[1])
      // )[0];
      // var lat = gcj02towgs84(
      //   parseFloat(item.location[0]),
      //   parseFloat(item.location[1])
      // )[1];
      var lon = item.location[0];
      var lat = item.location[1];
      console.log(lon, lat);
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(lon, lat, 2000.0),
      });
      if (!IconLocateLayer) {
        IconLocateLayer = CesiumUtil.CreateLayer("IconLocateLayer");
      } else {
        CesiumUtil.LayerRemoveAll(IconLocateLayer);
      }
      let cartographics = [Cesium.Cartographic.fromDegrees(lon, lat)];
      var pointHeight = null;
      Cesium.sampleTerrain(viewer.terrainProvider, 12, cartographics).then(
        (updatedPositions) => {
          updatedPositions.forEach((pos, i) => {
            pointHeight = pos.height;
            console.log(pos.height);
          });
        }
      );
      setTimeout(function () {
        var mark = {
          id: "",
          name: "",
          type: "iconlocate",
          longitude: lon,
          latitude: lat,
          height: pointHeight ? pointHeight + 10 : 100,
          scale: 0.5,
          pixelOffset: [0.0, -10.0],
          distanceShow: [0, 1000000],
          icon: require("@/assets/icons/topointicon.png"),
        };
        CesiumUtil.AddMark(mark, IconLocateLayer);

        _this.isShowSearchName = false;
      }, 1500);
    },
    searchName() {
      var _this = this;
      _this.isShowSearchName = true;
      // 判断是否有搜索字段
      if (_this.inputName === undefined || !_this.inputName) {
        _this.searchPointsList = [];
        _this.showHideSearchHistory(true);
        return false;
      }
      var locations = localStorage.getItem("org_lat_lng");

      // 请求接口
      locationDistrict({
        address: _this.inputName,
        city: this.orgInfo ? this.orgInfo.org_city : "衢州",
        // locations: locations ? locations : "",
      })
        .then((res) => {
          if (res.msg === "ok") {
            if (res.data && _this.inputName) {
              _this.searchPointsList = res.data;
            } else {
              _this.searchPointsList = [];
            }
            if (_this.searchPointsList.length > 0) {
              _this.showHideSearchHistory(false);
            }
          } else {
            _this.searchPointsList = [];
          }
        })
        .catch((err) => {
          _this.searchPointsList = [];
        });
    },

    isShowModule(val) {
      this.isVisible = val;
    },
    changeModule(val) {
      if (this.moduleIndex != val) {
        this.moduleIndex = val;
      }
      this.$bus.emit("closeQj");
    },
    // 搜索历史
    historySearch(queryString, cb) {
      const res = sessionStorage.getItem("rightSearchHistory");
      if (!res) {
        cb([]);
      } else {
        cb(JSON.parse(res));
      }
    },
    handleSelectHistory(item) {
      console.log("handleSelectHistory", item);
      this.inputName = item;
      this.searchName();
    },
    saveHistory(str) {
      if (str.trim()) {
        let res = sessionStorage.getItem("rightSearchHistory");
        console.log("saveHistory2", res);
        if (res) {
          res = JSON.parse(res);
          console.log("saveHistory4", res);
        } else {
          res = [];
          console.log("saveHistory3", res);
        }
        console.log("saveHistory5", res);
        if (res.includes(str.trim())) {
          const newArray = [];
          res.forEach((item) => item !== str.trim() && newArray.push(item));
          res = newArray;
        }
        res.unshift(str.trim());
        if (res.length > 5) {
          res = res.slice(0, 5);
        }
        sessionStorage.setItem("rightSearchHistory", JSON.stringify(res));
      }
    },
    showHideSearchHistory(flag) {
      if (
        this.$refs.inputRefsearchInfo &&
        this.$refs.inputRefsearchInfo.$refs.suggestions
      ) {
        const el = this.$refs.inputRefsearchInfo.$refs.suggestions.$el;
        if (flag) {
          el.style.visibility = "visible";
        } else {
          el.style.visibility = "hidden";
        }
      }
    },
  },
  watch: {
    moduleIndex(val) {
      this.$bus.emit("changeModuleIndex", val);
    },
    inputName(val) {
      console.log(val);
      if (val == "") {
        if (IconLocateLayer) {
          CesiumUtil.LayerRemoveAll(IconLocateLayer);
        }
      }
    },
  },
  beforeDestroy() {
    var that = this;
    this.removeBus();
    window.removeEventListener("keyup", that.KeyDownKeyword, true);
  },
};
</script>

<style scoped lang="scss">
.moveR1-enter-active,
.moveR1-leave-active {
  transition: all 0.3s ease;
  transform: translateX(0);
}

.moveR1-enter,
.moveR1-leave {
  transform: translateX(200%);
}

.moveR1-leave-to {
  transform: translateX(200%);
}

.showbtn {
  position: absolute;
  top: 70px;
  right: 10px;
  height: 30px;
  width: 30px;
  background: rgba(15, 57, 102, 0.8);
  padding: 0 5px;
  border: 1px solid rgba(28, 193, 255, 0.6);
  font-size: 18px;
  line-height: 30px;
  color: #f4f4f5;
  cursor: pointer;
  z-index: 100;
}

.container {
  position: absolute;
  // caret-color: transparent;
  top: vh(60);
  right: 20px;
  height: vh(1000);
  transition: all 0.5s;
  z-index: 999;
  box-sizing: border-box;
  width: 330px;
  transition: 0.2s cubic-bezier(0, 0, 0.2, 1);
  display: flex;
  flex-direction: column;

  .title {
    background-image: url("~@/assets/top_bg.png");
    height: vh(36);
    line-height: vh(20);
    padding: 0 vw(20);
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    border: 1px solid rgba(28, 193, 255, 0.2);
    position: relative;
    .t {
      margin-top: 10px;
      color: rgba(227, 227, 227, 0.8);
      cursor: pointer;

      &.active {
        color: #fff;
        font-size: 15px;
      }
    }

    .titleText {
      flex: 1;
      display: flex;
      justify-content: space-evenly;
    }

    .icon {
      font-size: 20px;
      width: 10px;
    }
  }

  .box {
    position: relative;
    background: rgba(5, 29, 40, 0.8);
    margin-top: -1px;
    border: 1px solid rgba(28, 193, 255, 0.2);
    flex: 1;
    height: 0;
    background-image: url("~@/assets/z2.png");
    background-size: 100% vh(60);
    background-repeat: no-repeat;
    background-position: 0 vh(905);
    box-shadow: 0 0 vh(15) rgba(28, 193, 255, 0.4) inset;
  }
}

.container_right {
  z-index: 1000;
}

.toolBox {
  position: absolute;
  font-size: 14px;
  right: 360px;
  top: vh(80);
  display: flex;
  flex-direction: column;
  align-items: end;
  &.searchToolBox {
    right: 45px;
    top: 70px;
  }
  .searchBox {
    .searchInfoBtn {
      width: 30px;
      color: #ffffff;
      background: #14375d;
      border: 1px solid #1989be;
      width: 32px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      cursor: pointer;
      border-right: none;
    }
    .searchInfo {
      display: flex;
      flex-direction: row-reverse;
    }

    .searchList {
      background: rgba(5, 29, 40, 0.8);
      border: 1px solid rgba(28, 193, 255, 0.2);
      color: #ffffff;
      padding: 5px 15px 5px 25px;
      box-sizing: border-box;
      margin-top: 5px;
      max-height: 600px;
      overflow: auto;

      > div {
        border-bottom: 1px solid #7e878b;
        padding: 5px 0;
        cursor: pointer;
        position: relative;
        text-indent: 3px;

        .iconp {
          position: absolute;
          left: -22px;
          top: 10px;
        }

        > div:last-child {
          font-size: 12px;
          color: #d3d3d3;
        }
      }

      > div:hover {
        background: rgba(173, 196, 207, 0.36);
      }
    }

    .searchBtn {
      color: #ffffff;
      background: #14375d;
      border: 1px solid #1989be;
      // border-right: none;
      display: inline-block;
      width: 32px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      cursor: pointer;
      border-radius: 0px 2px 2px 0;

      i {
        font-size: 16px;
      }
    }
  }

  .measureBox {
  }
}

.searchBox::v-deep {
  .el-input {
    width: 290px;

    .el-input__inner {
      background: rgba(0, 0, 0, 0.3);
      height: 30px;
      border: 1px solid #1989be;
      border-right: none;
      border-radius: inherit;
      color: #ffffff;
      border-radius: 2px 0px 0px 2px;
    }

    .el-input__suffix {
      .el-input__suffix-inner {
        .el-input__clear {
          line-height: 30px;
        }
      }
    }
  }
}

.historyItem {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  background-color: rgba(0, 0, 0, 0);
  color: white;
  padding: 8px;

  .history-icon {
    width: 15px;
    height: 15px;
    margin-right: 8px;
  }

  .history-text {
    font-size: 13px;
    line-height: 15px;
    align-content: center;
    overflow: hidden; /* 超出一行文字自动隐藏 */
    text-overflow: ellipsis; /*文字隐藏后添加省略号*/
    white-space: nowrap; /*强制不换行*/
  }
}
</style>
